<template>
  <div>
    <div class="equip-wrap-common">
      <px-button style="margin-top: 24px; margin-bottom: -8px" icon="ArrowLeft" type="primary" @click="backMainPage">返回 </px-button>
      <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px" style="padding-top: 24px">
        <px-row :gutter="16">
          <px-col :span="8">
            <px-form-item label="厂商名称">
              <px-input
                v-model="queryParams.enterpriseName"
                placeholder="请输入厂商名称"
                maxlength="50"
                clearable
                @blur="queryParams.enterpriseName = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="8">
            <px-form-item label="姓名">
              <px-input
                v-model="queryParams.contactName"
                placeholder="请输入姓名"
                maxlength="50"
                clearable
                @blur="queryParams.contactName = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="5">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
          <px-col :span="3" style="text-align: right">
            <px-button v-has="'ALL_BENCH_TASK_PHONEBOOK_ADD'" type="primary" @click="handleEdit()">新增</px-button>
          </px-col>
        </px-row>
      </px-form>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 303px)" border>
        <px-table-column label="序号" min-width="50" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column prop="enterpriseName" label="厂商名称" min-width="200" fixed="left" show-overflow-tooltip />
        <px-table-column prop="contactName" label="联系人姓名" min-width="120" show-overflow-tooltip />
        <px-table-column prop="phone" label="联系电话" min-width="180" show-overflow-tooltip />
        <px-table-column prop="createTime" label="创建时间" min-width="180" />
        <px-table-column prop="createByName" label="创建人" min-width="180" />
        <px-table-column prop="sourceDesc" label="来源" min-width="180" />
        <px-table-column align="center" label="操作" min-width="150" fixed="right">
          <template #default="scope">
            <px-tooltip v-if="!scope.row.isFix" content="固定到首页" placement="top">
              <px-button v-has="'ALL_BENCH_TASK_PHONEBOOK_COMMONLY'" link type="primary" @click.stop="handleCreateHotline(scope.row)">
                <DingSvg class="ding" />
              </px-button>
            </px-tooltip>
            <px-tooltip v-if="scope.row.isFix" content="取消固定到首页" placement="top">
              <px-button v-has="'ALL_BENCH_TASK_PHONEBOOK_COMMONLY_CANCEL'" link type="primary" @click="handleDeleteCollectPhone(scope.row)">
                <NoTopSvg class="content-icon" />
              </px-button>
            </px-tooltip>
            <px-tooltip v-if="!scope.row.isUse" content="设为常用电话" placement="top">
              <px-button v-has="'ALL_BENCH_TASK_PHONEBOOK_COMMONLY_USE'" link type="primary" @click.stop="handleUse(scope.row)">
                <CySvg class="ding" />
              </px-button>
            </px-tooltip>
            <px-tooltip v-if="scope.row.isUse" content="取消常用电话" placement="top">
              <px-button v-has="'ALL_BENCH_TASK_PHONEBOOK_COMMONLY_CANCEL_USE'" type="primary" link @click.stop="handleCancelUse(scope.row)">
                <QxcySvg class="ding" />
              </px-button>
            </px-tooltip>
            <px-tooltip v-if="scope.row.source === 'personal'" content="编辑" placement="top">
              <px-button v-has="'ALL_BENCH_TASK_PHONEBOOK_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.source === 'personal'" content="删除" placement="top">
              <px-button v-has="'ALL_BENCH_TASK_PHONEBOOK_DELE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
      <px-dialog v-model="visible" destroy-on-close class="equip-dialog-wrap" :title="title" width="600px" @close="closeDialog">
        <px-form ref="formRef" :rules="rules" :model="formValue" label-width="100px">
          <px-form-item prop="enterpriseName" label="厂商名称">
            <px-input
              v-model="formValue.enterpriseName"
              placeholder="请输入厂商名称"
              maxlength="50"
              @blur="formValue.value = $event.target.value.trim()"
            />
          </px-form-item>
          <px-form-item prop="contactName" label="联系人姓名">
            <px-input
              v-model="formValue.contactName"
              placeholder="请输入联系人姓名"
              maxlength="50"
              @blur="formValue.value = $event.target.value.trim()"
            />
          </px-form-item>
          <px-form-item prop="phone" label="联系人电话">
            <px-input v-model="formValue.phone" placeholder="请输入联系人电话" maxlength="50" @blur="formValue.value = $event.target.value.trim()" />
          </px-form-item>
          <div class="equip-dialog-btn">
            <px-button @click="closeDialog">取消</px-button>
            <px-button type="primary" @click="handleSubmmit">确定</px-button>
          </div>
        </px-form>
      </px-dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ALL_BENCH_TASK_PHONEBOOK"
});
import {
  createCommunication_1,
  createEnterprise,
  deleteCollectPhone,
  deleteCommunication,
  deleteEnterprise,
  fixedCommunication,
  pageEnterprise,
  updateEnterprise
} from "@/api/bench";
import CySvg from "@/assets/svg/bench/cy.svg?component";
import DingSvg from "@/assets/svg/bench/ding.svg?component";
import NoTopSvg from "@/assets/svg/bench/noTop.svg?component";
import QxcySvg from "@/assets/svg/bench/qxcy.svg?component";
import { stringTrimOfParams } from "@/utils/common";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const formRef = ref();
const formValue: any = ref({});
const state = reactive<any>({
  tabList: [],
  activeName: "UNDO",
  title: "新增联系人",
  queryParams: {
    enterpriseName: "",
    contactName: "",
    pageNum: 1,
    pageSize: 20
  },
  tableData: [],
  total: 0,
  visible: false,
  rules: {
    enterpriseName: [
      {
        required: true,
        message: "值不能为空",
        trigger: "blur"
      }
    ],
    contactName: [
      {
        required: true,
        message: "值不能为空",
        trigger: "blur"
      }
    ],
    phone: [
      {
        required: true,
        message: "值不能为空",
        trigger: "blur"
      }
    ]
  }
});
const { queryParams, tableData, total, visible, rules, title } = toRefs(state);

// 进入页面时触发
onMounted(async () => {
  queryTable();
});
const backMainPage = () => {
  router.push("/all/bench/home");
};
// 通讯录-设为常用
const handleUse = async row => {
  await createCommunication_1(row);
  PxMessage.success("已设为常用");
  queryTable();
};
const handleCancelUse = async row => {
  await deleteCommunication(row);
  PxMessage.success("已取消设为常用");
  queryTable();
};
// 通讯录-固定到首页
const handleCreateHotline = async row => {
  const { contactName, enterpriseName, enterpriseNo } = row;
  const params = {
    ...row,
    empNo: enterpriseNo,
    relatedName: enterpriseName,
    name: contactName
  };
  await fixedCommunication(params);
  PxMessage.success("已固定到首页");
  queryTable();
};
// 通讯录-取消固定到首页
const handleDeleteCollectPhone = async row => {
  const { enterpriseNo, id } = row;
  const params = {
    empNo: enterpriseNo,
    id
  };
  await deleteCollectPhone(params);
  PxMessage.success("已取消固定到首页");
  queryTable();
};
// 查询列表
const queryTable = async () => {
  const params = queryParams.value;
  const data: any = await pageEnterprise(stringTrimOfParams(params));
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 重置筛选条件和列表
const resetTable = async () => {
  queryParams.value = {
    enterpriseName: "",
    contactName: "",
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};
const handleSubmmit = () => {
  formRef.value.validate(async flag => {
    if (flag) {
      if (title.value === "新增联系人") {
        await createEnterprise(formValue.value);
      } else {
        await updateEnterprise(formValue.value);
      }
      PxMessage.success(`${title.value}成功`);
      closeDialog();
      queryTable();
    }
  });
};
const handleDelete = row => {
  PxMessageBox.confirm(`删除后不可恢复，继续删除吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteEnterprise({ enterpriseNo: row.enterpriseNo });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
const handleEdit = (row?: object) => {
  if (row) {
    title.value = "编辑联系人";
    formValue.value = { ...row };
  } else {
    title.value = "新增联系人";
    formValue.value = {};
  }
  visible.value = true;
};
const closeDialog = () => {
  visible.value = false;
  formRef.value.resetFields();
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.equip-dialog-btn {
  text-align: right;
}

.ding {
  width: 14px;
  height: 14px;
  margin: 0 auto;
  cursor: pointer;
}
</style>
